package com.itheima.user.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.itheima.entity.UserEntity;
import com.itheima.feign.order.OrderFeign;
import com.itheima.user.service.UserService;
import com.itheima.vo.request.AddOrderVO;
import com.itheima.vo.response.OrderResultVO;
import com.itheima.vo.response.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
//@CrossOrigin  // 解决跨域问题
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("/hello")
    public String hello(String company, HttpServletRequest request){
        String token = request.getHeader("token");
        return "hello user service,company : "+company + "toekn ="+token;
    }

    //用户登录
    @GetMapping("/login/{userName}/{password}")
    public ResultVO login(@PathVariable("userName") String userName, @PathVariable("password") String password) {
        boolean loginResult = userService.login(userName, password);
        ResultVO result = new ResultVO();
        if (loginResult) {
            result.setSuccess(true);
        } else {
            result.setSuccess(false);
        }
        return result;
    }

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    OrderFeign orderFeign; // JDK动态代理， 底层基于 HTTP发起远程调用， 代理对象存到IOC容器


    @SentinelResource(value = "findUserOrderList")
    @GetMapping("/findUserOrderList")
    public OrderResultVO findUserOrderList(@RequestParam(value = "userId",required = false) Integer userId){

        if (userId==null){
            userId=1;
        }

        OrderResultVO orderResultVO = new OrderResultVO();
        UserEntity userEntity = userService.findUserById(userId);

        List list = orderFeign.findOrderInfoByUserId(userId);
        orderFeign.findAll();

        orderResultVO.setUserName(userEntity.getUserName());
        orderResultVO.setOrderList(list);

        return orderResultVO;
    }



    //查询用户订单信息
    @GetMapping("/findUserOrders/{userId}")
    public OrderResultVO findUserOrders(@PathVariable("userId") Integer userId) {

        OrderResultVO orderResultVO = new OrderResultVO();
        UserEntity userEntity = userService.findUserById(userId);

        // 远程调用根据用户ID查询订单列表
        /**
         * 1、IP和PORT硬编码
         * 2、请求的路径地址 硬编码
         * 3、集群无法实现负载均衡
         */
//        String url = "http://localhost:9001/order/findOrderInfoByUserId/" + userId;
//        List list = restTemplate.getForObject(url, List.class);


        // 解决 IP和PORT硬编码
//        List<ServiceInstance> instances = discoveryClient.getInstances("order-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        serviceInstance.getHost(); // IP
//        serviceInstance.getPort(); // PORT
//        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/order/findOrderInfoByUserId/" + userId;
//        List list = restTemplate.getForObject(url, List.class);

        // 解决 集群无法实现 负载均衡, 默认是 轮询算法
//        String url = "http://order-service/order/findOrderInfoByUserId/" + userId;
//        List list = restTemplate.getForObject(url, List.class);


        // 解决请求路硬编码
        List list = orderFeign.findOrderInfoByUserId(userId);
        orderFeign.findAll();

        orderResultVO.setUserName(userEntity.getUserName());
        orderResultVO.setOrderList(list);

        return orderResultVO;
    }

    //添加订单
    @PostMapping("/addUserOrder")
    public ResultVO addUserOrder(@RequestBody AddOrderVO addOrderVO) {
        ResultVO result = new ResultVO();
        //判断用户是否存在
        UserEntity userEntity = userService.findUserById(addOrderVO.getUserId());
        if (userEntity == null) {
            result.setSuccess(false);
            return result;
        }

        //todo

        return result;
    }
}
